﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;

namespace HealthCommunity
{
	public partial class GetPassword : System.Web.UI.Page
	{
		private IUserProvider _UserProvider;

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void btnNext_Click(object sender, EventArgs e)
		{
			if (_UserProvider == null)
			{
				_UserProvider = new UserProvider();
			}

			var theUser = _UserProvider.GetUser(txtUserName.Text.Trim());

			if (theUser != null)
			{
				ddlSecurityQuestion.Items.Clear();
				ddlSecurityQuestion.Items.Add(new ListItem(theUser.SecretQuestion1, "1"));
				ddlSecurityQuestion.Items.Add(new ListItem(theUser.SecretQuestion2, "2"));

				ddlSecurityQuestion.SelectedIndex = 0;

				divgetpwdstep1.Style.Add("display", "none");
				divsecuritycontainer.Style.Add("display", "");
			}
			else
			{
				ltrMsgStep1.Text = "用户名不存在";
			}
		}

		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			if (_UserProvider == null)
			{
				_UserProvider = new UserProvider();
			}

			var theUser = _UserProvider.GetUser(txtUserName.Text.Trim());

			if (theUser != null)
			{
				var tagSecurityAnswerPassed = false;

				if (ddlSecurityQuestion.SelectedValue.Contains("1"))
				{
					if (theUser.SecretAnswer1.Equals(txtSecurityAnswer.Text.Trim()))
					{
						tagSecurityAnswerPassed = true;
					}
					else
					{
						lblMsg.Text = "您输入的密码提示答案错误";
					}
				}
				else
				{
					if (theUser.SecretAnswer2.Equals(txtSecurityAnswer.Text.Trim()))
					{
						tagSecurityAnswerPassed = true;
					}
					else
					{
						lblMsg.Text = "您输入的密码提示答案错误";
					}
				}

				if (tagSecurityAnswerPassed)
				{
					theUser.UserPassword = Guid.NewGuid().ToString("N").Substring(0, 8);
					if (_UserProvider.ResetPassword(theUser))
					{
						var subject = "找回密码";
						var body = @"您的密码已重置为: " + theUser.UserPassword + ".";
						var to = theUser.Email;

						CommonHelper.SendMail(to, subject, body);
						lblMsg.Text = "密码已重置,新密码已发送至您的邮箱: " + theUser.Email + ", 请检查邮箱.";
					}
					else
					{
						lblMsg.Text = "无法重置密码";
					}
				}
			}
		}
	}
}